package com.furns.web; /**
 * @Author LuoJiaCheng
 * @ID 2240129126
 * @Version 1.0
 */

import com.furns.entity.Member;
import com.furns.service.MemberService;
import com.furns.service.impl.MemberServiceImpl;
import com.google.code.kaptcha.servlet.KaptchaServlet;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

@WebServlet(name = "MemberServlet", value = "/MemberServlet")
public class MemberServlet extends BasicServlet {
    private MemberServiceImpl memberService = new MemberServiceImpl();

    /**
     * 异步验证某个用户名是否已经存在
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isExistUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        boolean isExistUsername = memberService.isExistsUsername(username);
        //返回json格式的数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isExist",isExistUsername);
        String isExist= new Gson().toJson(resultMap);
        resp.getWriter().write(isExist);

    }


    /**
     * 异步验证验证码是否正确
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void isTrueCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String code = req.getParameter("code");
        System.out.println(code);
        //从session中获取到验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        System.out.println(token);
        Map<String, Object> resultMap = new HashMap<>();
        if (token != null && token.equalsIgnoreCase(code)) {
            resultMap.put("isTrue",true);
            String isTrue= new Gson().toJson(resultMap);
            resp.getWriter().write(isTrue);
        } else {
            resultMap.put("isTrue",false);
            String isTrue= new Gson().toJson(resultMap);
            resp.getWriter().write(isTrue);
        }

    }

    /**
     * 处理登录
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //接收用户登录信息
        String user_name = request.getParameter("user-name");
        String user_password = request.getParameter("user-password");
        //不为空，登陆成功
        Member member = memberService.login(new Member(null, user_name, user_password, null));
        if (member != null) {
            HttpSession session = request.getSession();
            session.setAttribute("member", member);
            request.getRequestDispatcher("/views/member/login_ok.jsp").forward(request, response);
        } else {
            //登陆失败，请求转发
            request.setAttribute("msg", "用户名或者密码错误");
            request.setAttribute("username", user_name);
            request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
        }
    }

    /**
     * 处理注册
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //接收用户注册信息
        String username = request.getParameter("username");
        String pwd = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");
        //从session中获取到验证码
        String token = (String) request.getSession().getAttribute(KAPTCHA_SESSION_KEY);
        //立即删除session验证码->防止该验证码被重复使用
        request.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        if (token != null && token.equalsIgnoreCase(code)) {
            //判断用户名是不是可用的
            if (!memberService.isExistsUsername(username)) {
                Member member = new Member(null, username, pwd, email);
                if (memberService.registerMember(member)) {
                    //请求转发
                    request.getRequestDispatcher("/views/member/register_ok.jsp").forward(request, response);
                } else {
                    //请求转发
                    request.getRequestDispatcher("/views/member/register_fail.jsp").forward(request, response);
                }
            } else {
                //请求转发
                request.setAttribute("msg", "用户名已存在");
                request.setAttribute("active", "register");
                request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
            }
            System.out.println("RegisterServlet被调用。。。。");
        } else {
            request.setAttribute("msg", "验证码不正确");
            request.setAttribute("active", "register");
            request.setAttribute("username", username);
            request.setAttribute("password", pwd);
            request.setAttribute("email", email);
            request.getRequestDispatcher("/views/member/login.jsp").forward(request, response);
        }


    }

    /**
     * 注销登录
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath());
    }
}
